<template>
  <el-form :inline="true" :model="tableForm" class="demo-form-inline">
    <el-form-item label="请输入">
      <el-input
        v-model="tableForm.prodName"
        placeholder="商品id/关键字/品牌名等"
        clearable
      />
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click="getList">查询</el-button>
    </el-form-item>
  </el-form>
  <el-button class="!ml-0" type="primary" plain @click="toSave">
    新增商品
  </el-button>
  <el-button class="!ml-0" type="warning" @click="open"> 批量删除 </el-button>
  <el-button class="!ml-0" type="warning" @click="EsOpen"> 批量添加 </el-button>
  <el-table
    :data="tableData"
    @selection-change="handleSelectionChange"
    :border="true"
    style="width: 100%"
  >
    <el-table-column type="selection" width="55" />
    <el-table-column prop="prodId" label="序号" />
    <el-table-column prop="prodSpu" label="SPU" />
    <el-table-column prop="typeName" label="分类" />
    <el-table-column prop="kindName" label="类型" />
    <el-table-column prop="prodName" label="名称">
      <template #default="scope">
        <span v-html="scope.row.prodName"></span>
      </template>
    </el-table-column>
    <el-table-column prop="brandName" label="品牌" />
    <el-table-column prop="prodStatus" label="状态">
      <template #default="scope">
        <el-tag type="primary" v-if="scope.row.prodStatus == 0">草稿</el-tag>
        <el-tag type="warning" v-if="scope.row.prodStatus == 1">待审核</el-tag>
        <el-tag type="success" v-if="scope.row.prodStatus == 2">已上架</el-tag>
        <el-tag type="danger" v-if="scope.row.prodStatus == 3">已下架</el-tag>
        <el-tag type="info" v-if="scope.row.prodStatus == 4">缺货</el-tag>
      </template>
    </el-table-column>
    <el-table-column prop="unitName" label="单位" />
    <el-table-column prop="tagName" label="标签" />
    <el-table-column prop="supplier" label="供应商" />
    <el-table-column prop="prodImage" label="缩略图">
      <template #default="scope">
        <el-image
          style="width: 100px; height: 100px"
          :src="scope.row.prodImage"
          :zoom-rate="1.2"
          :max-scale="7"
          :min-scale="0.2"
          show-progress
          :initial-index="4"
          fit="cover"
        />
      </template>
    </el-table-column>
    <el-table-column prop="createBy" label="创建人" />
    <el-table-column label="操作">
      <template #default="scope">
        <el-button class="!ml-0" type="info" plain @click="Toblank">
          商品
        </el-button>
        <br />
        <el-button
          class="!ml-0"
          type="success"
          plain
          @click="toFile(scope.row)"
        >
          商品附件
        </el-button>
      </template>
    </el-table-column>
  </el-table>
  <div class="demo-pagination-block">
    <el-pagination
      v-model:current-page="tableForm.pageNum"
      v-model:page-size="tableForm.pageSize"
      :page-sizes="[3, 6, 9, 12]"
      :background="true"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </div>
  <div>
    <el-dialog v-model="dialogFormVisible" title="填写信息" width="500">
      <el-form
        ref="ruleFormRef"
        style="max-width: 600px"
        :model="ruleForm"
        :rules="rules"
        label-width="auto"
      >
        <el-form-item label="商品类型" prop="prodKind">
          <el-radio-group v-model="ruleForm.prodKind" v-for="item in kindList">
            <el-radio :value="item.dictValue" :key="item.id" :size="large">{{
              item.dictName
            }}</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="商品分类" prop="prodType">
          <el-cascader v-model="ruleForm.prodType" :options="typeSelect" />
          <!-- <el-tree-select
            v-model="ruleForm.prodType"
            :data="typeSelect"
            :render-after-expand="false"
            style="width: 240px"
          /> -->
        </el-form-item>

        <el-form-item label="商品名称" prop="prodName">
          <el-input v-model="ruleForm.prodName" />
        </el-form-item>

        <el-form-item label="商品品牌" prop="prodBrand">
          <el-select
            v-model="ruleForm.prodBrand"
            placeholder="请选择"
            style="width: 240px"
          >
            <el-option
              v-for="item in brandSelect"
              :key="item.brandId"
              :label="item.brandName"
              :value="item.brandId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="商品单位" prop="unitId">
          <el-select
            v-model="ruleForm.unitId"
            placeholder="请选择"
            style="width: 240px"
          >
            <el-option
              v-for="item in unitSelect"
              :key="item.id"
              :label="item.dictName"
              :value="item.dictValue"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="商品标签" prop="tagId">
          <el-select
            v-model="ruleForm.tagId"
            placeholder="请选择"
            style="width: 240px"
          >
            <el-option
              v-for="item in tagSelect"
              :key="item.id"
              :label="item.dictName"
              :value="item.dictValue"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="供应商" prop="supplier">
          <el-input v-model="ruleForm.supplier" />
        </el-form-item>
        <el-form-item label="SPU" prop="prodSpu">
          <el-input v-model="ruleForm.prodSpu" />
        </el-form-item>
        <el-form-item label="缩略图" prop="prodImage">
          <el-upload
            class="avatar-uploader"
            action="http://localhost:10010/shop/index/uploadFile"
            :show-file-list="false"
            :headers="headers"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitForm(ruleFormRef)">
            确定
          </el-button>
          <el-button @click="resetForm(ruleFormRef)">重置</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
  <div>
    <el-dialog v-model="dialogFormFile" title="添加商品附件" width="500">
      <el-form
        ref="ruleFormRef"
        style="max-width: 600px"
        :model="fileForm"
        :rules="fileRules"
        label-width="auto"
      >
        <el-form-item label="轮播图片" prop="carouselImages">
          <el-upload
            v-model:file-list="fileList"
            action="http://localhost:10010/shop/index/uploadFile"
            list-type="picture-card"
            :on-success="handleAvatarSuccess"
            :headers="headers"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="轮播视频" prop="carouselImages">
          <el-upload
            v-model:file-list="videoList"
            class="upload-demo"
            action="http://localhost:10010/shop/index/uploadFile"
            multiple
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :before-remove="beforeRemove"
            :limit="3"
            :headers="headers"
            :on-exceed="handleExceed"
          >
            <el-button type="primary">点击上传</el-button>
            <template #tip> </template>
          </el-upload>
        </el-form-item>
        <el-form-item label="上架时间" prop="upFlag">
          <el-radio-group v-model="fileForm.upFlag">
            <el-radio value="0" size="large">立即上架</el-radio>
            <el-radio value="1" size="large">定时上架</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          label="上架时间"
          prop="upTime"
          v-if="fileForm.upFlag == 1"
        >
          <el-date-picker
            v-model="fileForm.upTime"
            type="datetime"
            placeholder="请选择"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="定时下架" prop="downFlag">
          <el-switch
            v-model="fileForm.downFlag"
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item>
        <el-form-item
          label="下架时间"
          prop="upTime"
          v-if="fileForm.downFlag == 1"
        >
          <el-date-picker
            v-model="fileForm.downTime"
            type="datetime"
            placeholder="请选择"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="fileSubmitForm(ruleFormRef)">
            确定
          </el-button>
          <el-button @click="closeFileDia">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import * as echarts from "echarts";
import { onMounted, ref } from "vue";
import {
  getDictValueByRedis,
  selectTypeList,
  getSelectBrand,
  checkIfRepeat,
  saveProduct,
  joinSelectProdList,
  saveProFileOk,
  deleteGoodsBatch,
  joinSelectProdListByEs,
  barchUpProd,
} from "../api/api";
import { ElMessage, ElMessageBox } from "element-plus";
import { Plus } from "@element-plus/icons-vue";

import type { UploadProps, UploadUserFile } from "element-plus";
const fileList = ref([]);
const tableData = ref([]);
const total = ref(0);
const imageUrl = ref("");
const dialogFormVisible = ref(false);
const dialogFormFile = ref(false);
const formLabelWidth = "140px";
import type { FormInstance, FormRules } from "element-plus";
const dialogImageUrl = ref("");
const dialogVisible = ref(false);
const ruleFormRef = ref<FormInstance>();
const multipleSelection = ref([]);
const ruleForm = ref({});
const tableForm = ref({
  keyWord: "",
  pageNum: 1,
  pageSize: 2,
});
const resetOne = () => {
  ruleForm.value = {
    prodKind: null,
    prodType: null,
    prodName: "",
    unitId: null,
    tagId: null,
    supplier: "",
    prodSpu: "",
    prodImage: "",
  };
  imageUrl.value = "";
};
const resetTwo = () => {
  fileForm.value = {
    upFlag: "",
    upTime: "",
    downFlag: "",
    downTime: "",
  };
  fileList.value = [];
  videoList.value = [];
};
const fileForm = ref({
  carouselImages: "",
  carouselVideo: "",
});

const open = () => {
  if (multipleSelection.value.length <= 0) {
    ElMessage.error("请先选择数据");
    return;
  }
  ElMessageBox.confirm("操作后不能恢复，确定要删除?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      let ids = [];
      multipleSelection.value.forEach((item) => {
        ids.push(item.prodId);
        deleteGoodsBatch(ids).then((res) => {
          if (res.data.flag) {
            ElMessage.success("成功操作" + ids.length + "条数据");
            getList();
          } else {
            ElMessage.error(res.data.msg);
          }
        });
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "操作取消",
      });
    });
};
const EsOpen = () => {
  if (multipleSelection.value.length <= 0) {
    ElMessage.error("请先选择需要上架的商品");
    return;
  }
  let ids = [];
  multipleSelection.value.forEach((item) => {
    ids.push(item.prodId);
  });
  barchUpProd(ids).then((res) => {
    if (res.data.flag) {
      ElMessage.success("上架成功");
      getList();
    }
  });
};

const toFile = (row: any) => {
  dialogFormFile.value = true;
  fileForm.value.prodId = row.prodId;
};
const closeFileDia = () => {
  dialogFormFile.value = false;
  resetTwo;
};
const headers = ref({
  token: sessionStorage.getItem("token"),
});

const toSave = () => {
  dialogFormVisible.value = true;
  // console.log("radio", kindList.value);
  console.log("select", prodTypeSelect);
};

const checkRepeat = (rule: any, value: any, callback: any) => {
  if (!value) {
    return callback(new Error("商品SPU不能为空"));
  }
  let form = {
    prodSpu: value,
  };
  checkIfRepeat(form).then((res) => {
    if (!res.data.flag) {
      callback(new Error("该条信息已经存在"));
    } else {
      callback();
    }
  });
};

const getList = () => {
  joinSelectProdListByEs(tableForm.value).then((res) => {
    tableData.value = res.data.data.records;
    total.value = res.data.data.total;
  });
};

const rules = ref({
  prodKind: [{ required: true, message: "商品类型不能为空", trigger: "blur" }],
  prodName: [
    { required: true, message: "商品名称不能为空", trigger: "blur" },
    {
      pattern: /^[\u4E00-\u9FA5A-Za-z0-9_]+$/,
      message: "商品名称不能包含特殊符号",
      trigger: "blur",
    },
  ],
  prodType: [{ required: true, message: "商品分类不能为空", trigger: "blur" }],
  prodBrand: [{ required: true, message: "商品品牌不能为空", trigger: "blur" }],
  unitId: [{ required: true, message: "商品单位不能为空", trigger: "blur" }],
  tagId: [{ required: true, message: "商品标签不能为空", trigger: "blur" }],
  supplier: [{ required: true, message: "供应商不能为空", trigger: "blur" }],
  prodImage: [{ required: true, message: "缩略图不能为空", trigger: "blur" }],
  prodSpu: [{ validator: checkRepeat, trigger: "blur" }],
});

const fileRules = ref({
  carouselImages: [
    { required: true, message: "轮播图片不能为空", trigger: "blur" },
  ],
  carouselVideo: [{ required: true, message: "视频不能为空", trigger: "blur" }],
  upFlag: [{ required: true, message: "请选择上架时间", trigger: "blur" }],
});

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  ruleForm.value.prodType = ruleForm.value.prodType[1];
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log("submit!");
      saveProduct(ruleForm.value).then((res) => {
        if (res.data.flag) {
          ElMessage.success("添加成功");
          dialogFormVisible.value = false;
          getList();
          resetOne();
        } else {
          ElMessage.error(res.data.msg);
          console.log("image", ruleForm.value.prodImage);
        }
      });
    } else {
      console.log("error submit!", fields);
    }
  });
};

const fileSubmitForm = async (formEl: FormInstance | undefined) => {
  // 先判轮播图和视频
  let list: any = [];
  if (fileList.value.length <= 0) {
    ElMessage.error("请先上传轮播图片");
    return;
  }
  fileList.value.forEach((item) => {
    list.push(item.response.data);
  });
  fileForm.value.carouselImages = JSON.stringify(list);

  if (videoList.value.length <= 0) {
    ElMessage.error("请先上传视频");
  }
  fileForm.value.carouselVideo = JSON.stringify(
    videoList.value[0].response.data
  );
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log("submit!");
      saveProFileOk(fileForm.value).then((res) => {
        if (res.data.flag) {
          ElMessage.success("保存成功");
          dialogFormFile.value = false;
          resetTwo();
        } else {
          ElMessage.error(res.data.msg);
        }
      });
    } else {
      console.log("error submit!", fields);
    }
  });
};

const resetForm = (formEl: FormInstance | undefined) => {
  imageUrl.value = "";
  if (!formEl) return;
  formEl.resetFields();
};

const handleAvatarSuccess: UploadProps["onSuccess"] = (
  response,
  uploadFile
) => {
  imageUrl.value = response.data;
  ruleForm.value.prodImage = imageUrl.value;
};

const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile) => {
  if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error("上传文件大小不能超过 2MB!");
    return false;
  }
  return true;
};
const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`);
  getList();
};
const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`);
  getList();
};
const videoList = ref([]);

const handleRemove: UploadProps["onRemove"] = (file, uploadFiles) => {
  console.log(file, uploadFiles);
};

const handlePreview: UploadProps["onPreview"] = (uploadFile) => {
  console.log(uploadFile);
};

const handleExceed: UploadProps["onExceed"] = (files, uploadFiles) => {
  ElMessage.warning(
    `The limit is 3, you selected ${files.length} files this time, add up to ${
      files.length + uploadFiles.length
    } totally`
  );
};

const beforeRemove: UploadProps["beforeRemove"] = (uploadFile, uploadFiles) => {
  return ElMessageBox.confirm(
    `Cancel the transfer of ${uploadFile.name} ?`
  ).then(
    () => true,
    () => false
  );
};
const handleSelectionChange = (val: any) => {
  multipleSelection.value = val;
};

const kindList = ref([]);
const typeSelect = ref([]);

const brandSelect = ref([]);
const unitSelect = ref([]);
const tagSelect = ref([]);
// 页面加载钩子函数
onMounted(() => {
  getDictValueByRedis(1).then((res) => {
    kindList.value = res.data.data;
  });
  let form = {};
  selectTypeList(form).then((res) => {
    typeSelect.value = res.data.data;
  });
  getSelectBrand().then((res) => {
    brandSelect.value = res.data.data;
  });
  getDictValueByRedis(2).then((res) => {
    unitSelect.value = res.data.data;
  });
  getDictValueByRedis(3).then((res) => {
    tagSelect.value = res.data.data;
  });
  getList();
});
</script>
<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
